Page({
  data: {
    records: []
  },

  onLoad() {
    this.fetchPointsHistory();
  },

  // 返回上一页
  onBackTap() {
    wx.navigateBack();
  },

  // 获取积分记录
  fetchPointsHistory() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }

    wx.showLoading({
      title: '加载中...'
    });

    wx.request({
      url: 'https://www.haoyuming.online/api/user/points/history',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 401) {
          // 清除登录信息
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          // 显示提示
          wx.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });
          // 跳转登录页
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }, 1500);
          return;
        }
        
        if (res.data.code === 200) {
          // 格式化时间
          const records = res.data.data.map(record => ({
            ...record,
            createdAt: this.formatTime(record.createdAt)
          }));
          
          this.setData({
            records: records
          });
        } else {
          wx.showToast({
            title: res.data.msg || '获取记录失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 格式化时间
  formatTime(dateStr) {
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hour = date.getHours().toString().padStart(2, '0');
    const minute = date.getMinutes().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}`;
  }
}); 